import requests
import re
import json
import time
import os


from retrying import retry


def get_token():
    url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/yqfkdaka/state/%2Fhome.html'
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': 'cas.dgut.edu.cn',
        'Referer': 'https://yqfk-daka.dgut.edu.cn/',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
    }
    reposed = requests.get(url=url, headers=headers)
    reposed_token = str(reposed.content)
    # print(reposed_token)
    reposed_cookies = reposed.cookies.get_dict()
    token = re.findall(r'var token = "(.+?)";', reposed_token)
    print(f'token={token[0]}')
    return token[0], reposed_cookies


def get_token2(user, password):
    token1, cookie = get_token()
    url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/yqfkdaka/state/%2Fhome.html'
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': 'cas.dgut.edu.cn',
        'Referer': 'https://yqfk-daka.dgut.edu.cn/',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
    }
    data = {
        'username': user,
        'password': password,
        '__token__': token1,
        'wechat_verify': '',
    }
    reposed = requests.post(url=url, headers=headers, data=data, cookies=cookie).json()
    # print(reposed)
    token2 = re.findall(r'token=(.+?)&', reposed['info'])
    msg = reposed['message']
    # print(token2[0])
    print(msg)
    print(f'token2={token2[0]}')
    return token2[0], cookie


def get_access_token(user, password):
    token2, cookie = get_token2(user, password)
    url = 'https://yqfk-daka-api.dgut.edu.cn/auth'
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '70',
        'Content-Type': 'application/json',
        'Host': 'yqfk-daka-api.dgut.edu.cn',
        'Origin': 'https://yqfk-daka.dgut.edu.cn',
        'Referer': 'https://yqfk-daka.dgut.edu.cn/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
    }
    data = {
        'state': 'home',
        'token': token2,
    }
    data_json = json.dumps(data)
    access_token = requests.post(url=url, headers=headers, data=data_json, cookies=cookie).json()
    print(f"access_token={access_token['access_token']}")
    return access_token['access_token'], cookie


def get_data(user, password):
    url = 'https://yqfk-daka-api.dgut.edu.cn/record/'
    access_token, cookie = get_access_token(user, password)
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Authorization': f'Bearer {access_token}',
        'Connection': 'keep-alive',
        # 'Content-Length': '1650',
        'Content-Type': 'application/json',
        'Host': 'yqfk-daka-api.dgut.edu.cn',
        'Origin': 'https://yqfk-daka.dgut.edu.cn',
        'Referer': 'https://yqfk-daka.dgut.edu.cn/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
    }
    # print(data)
    # print(data_json)
    responed = requests.get(url=url, headers=headers)
    # print(responed.status_code)
    user_data = responed.json()['user_data']
    # print(responed.json()['user_data'])
    data = {"data": user_data}
    return data, access_token


def qiandao(user, password):
    url = 'https://yqfk-daka-api.dgut.edu.cn/record/'
    data, access_token = get_data(user, password)
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Authorization': f'Bearer {access_token}',
        'Connection': 'keep-alive',
        'Content-Length': '1650',
        'Content-Type': 'application/json',
        'Host': 'yqfk-daka-api.dgut.edu.cn',
        'Origin': 'https://yqfk-daka.dgut.edu.cn',
        'Referer': 'https://yqfk-daka.dgut.edu.cn/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
    }
    datatimenow = time.strftime("%Y-%m-%d", time.localtime())
    data['data']['submit_time'] = datatimenow
    data_json = json.dumps(data)
    # print(data)
    # print(data_json)
    responed = requests.post(url=url, headers=headers, data=data_json)
    # print(responed.status_code)
    te = '【' + data['data']['name'] + '】' + responed.json()['message']
    print(te + '\n' + datatimenow)
    print('---------------------------------------------------')
    return te


# 通知
class WXPusher:
    def __init__(self, usr, msg):
        self.base_url = ''
        self.req_url = ''
        self.corpid = ''  # 上面提到的你的企业ID
        self.corpsecret = ''  # 上图的Secret
        self.agentid = 565  # 填写你的企业ID，不加引号，是个整型常数,就是上图的AgentId
        self.usr = usr
        self.msg = msg

    def get_access_token(self):
        urls = self.base_url + 'corpid=' + self.corpid + '&corpsecret=' + self.corpsecret
        resp = requests.get(urls).json()
        access_token = resp['access_token']
        return access_token

    def send_message(self):
        data = self.get_message()
        req_urls = self.req_url + self.get_access_token()
        res = requests.post(url=req_urls, data=data)
        print('通知发送成功！！')
        # print(res.text)

    def get_message(self):
        data = {
            "touser": self.usr,
            "toparty": "@all",
            "totag": "@all",
            "msgtype": "mpnews",
            "agentid": self.agentid,
            "mpnews": {
                'articles': [
                    {
                        'title': '健康打卡',
                        'author': 'ZHZ',
                        'thumb_media_id': '2NStoYRzJQfXyw1yUmek79OKc4IDgoJvLkOzkGMmthncovvRUmHtTBRcGA7_sR82x',
                        'content_source_url': 'https://yqfk-daka.dgut.edu.cn/',
                        'content': f'{self.msg}',
                        'digest': f'{self.msg}'
                    }
                ]
            },
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }
        data = json.dumps(data)
        return data


def start(text):
    datatimenow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # 为账号添加通知
    test = WXPusher(usr='', msg=text + '\n' + datatimenow)  # usr参数为推送用户名，msg为消息文本
    test.send_message()


@retry  # 若出现异常，则重试
def main():
    # 解除以下注释用于本地测试
    # 逗号是英文的逗号
    os.environ['USER'] = USER
    text = ''
    userss = os.environ['USER']
    users = userss.split('&')
    for user in users:
        name, pwd = user.split(',')
        text = text + qiandao(name, pwd) + '\n'
    if NOTICE == 1:
        start(text)


# NOTICE 1 为企业微信通知，需要配置企业微信， 0 为不通知 不需要配置企业微信
# USER 为中央账号和密码 格式为 '账号,密码' 若需要配置多个账号，则用 & 连接 如 '账号1,密码1&账号2,密码2'
NOTICE = 0
USER = ''
main()
